package cn.edu.dlut.ssdut.foodCredit2012.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.PotentialUser;
import cn.edu.dlut.ssdut.foodCredit2012.model.User;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class PotentialUserService {
	private PotentialUser u = new PotentialUser();
	private UserService us = new UserService();
	
	public void add(PotentialUser u)throws Exception{
		if(!isPotentialUser(u)) {
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(u);
			session.getTransaction().commit();
		}
	}
	
	
	
	public PotentialUser load(PotentialUser u) throws Exception {
		if(isPotentialUser(u)){
			u = loadByLicenceID(u.getLicenceID());
			return u;
		}
		return u;
	}
	
	public PotentialUser loadByLicenceID(String licenceID) throws Exception{
		PotentialUser u = new PotentialUser();
		
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		u=(PotentialUser)session.get(PotentialUser.class, licenceID);
		
			
		session.getTransaction().commit();
		
		return u;
	}
	
	
	public void delete(PotentialUser u) throws Exception{
		boolean exist = isPotentialUser(u);
		if(exist) {
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(u);
			session.getTransaction().commit();
		}
	}
	
	public boolean isUser(PotentialUser pu) throws Exception{
		User u = new User();
		u.setLicenceID(pu.getLicenceID());
		u.setName(pu.getName());
		
		if(this.us.isUser(u)) return true;
		return false;
	}
	
	
	public List<PotentialUser> userList() {
		List<PotentialUser> userPList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from PotentialUser");
		query.setFirstResult(0);
		query.setMaxResults(20);
		userPList = (List<PotentialUser>)query.list();
		
		session.getTransaction().commit();
		
		return userPList;
	}
	
	
	
	public boolean isPotentialUser(PotentialUser u) throws Exception {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from PotentialUser u where u.licenceID = :licenceID")
			.setString("licenceID", u.getLicenceID())
			.uniqueResult();
		
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}



	public PotentialUser getU() {
		return u;
	}



	public void setU(PotentialUser u) {
		this.u = u;
	}



	public UserService getUs() {
		return us;
	}



	public void setUs(UserService us) {
		this.us = us;
	}
	
	

}
